package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author nanfeng
 * @since 2022-02-25
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //参数校验
        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCode.ERROR, "参数不能为空");
        }

        //校验验证码
        String mobleCode = redisTemplate.opsForValue().get("code:" + phone);
        if (!code.equals(mobleCode)) {
            throw new YyghException(20012, "验证码不正确");
        }

        //判断账户是否已存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);

        //判断账户是否被禁用(锁定)
        if (userInfo.getStatus() == 0 && userInfo != null) {
            throw new YyghException(ResultCode.ERROR, "账户已被禁用");
        }

        //账户不存在则注册,存在则登录
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setName(phone);
            userInfo.setNickName(phone); //昵称
            userInfo.setStatus(1);  //未锁定
            baseMapper.insert(userInfo);
        }

        //生成访问令牌
        String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());

        HashMap<String, Object> map = new HashMap<>();

        map.put("token", token); // TODO 访问令牌
        map.put("name", userInfo.getName());
        return map;
    }
}
